package com.muqi.app.qlearn.student.ui;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.muqi.app.im.adapter.SearchFriendsAdapter;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.modles.PersonBean;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;

public class AddChildActivity extends BaseFragmentActivity implements
		OnEditorActionListener, OnItemClickListener,
		SearchFriendsAdapter.AddFriendsListener {
	private EditText find_input;
	private ListView searchListView;
	private List<PersonBean> resultList = new ArrayList<PersonBean>();
	private SearchFriendsAdapter mAdapter = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_add_friends);
	}

	@Override
	protected void onInit() {
		find_input = (EditText) findViewById(R.id.find_friends_input);
		find_input.setOnEditorActionListener(this);
		searchListView = (ListView) findViewById(R.id.search_list_view);
		searchListView.setOnItemClickListener(this);
		((TextView)findViewById(R.id.tv_title)).setText("添加孩子");
	}

	@Override
	protected void onData() {

	}

	public void onSearch(View v) {
		if (TextUtils.isEmpty(find_input.getText().toString())) {
			find_input.setError("内容不能为空");
		} else {
			dismissSoftKeyboard();
			searchingFriends(find_input.getText().toString());
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH) {
			if (TextUtils.isEmpty(find_input.getText().toString())) {
				find_input.setError("内容不能为空");
			} else {
				searchingFriends(find_input.getText().toString());
			}
			return true;
		}
		return false;
	}

	private void searchingFriends(final String nickName) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("token", mSpUtil.getToken());
			map.put("str", nickName);
			String requestApi = ParamsUtils.buildParams(
					NetWorkApi.SEARCH_FRIENDS_API, map);
			MyAsyncHttp.get(this, requestApi, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						try {
							JSONObject resultJSON = new JSONObject(result);
							resultList.clear();
							JSONArray dataArray = resultJSON
									.getJSONArray("data");
							for (int i = 0; i < dataArray.length(); i++) {
								PersonBean item = PersonBean.fromJson(dataArray
										.optJSONObject(i));
								if (item != null)
									resultList.add(item);
							}
							if(resultList!=null && resultList.size()>0){
								showSearchResultView();
							}else{
								ShowToast.showShort(mContext, "未找到相关信息");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);
		}
	}

	private void showSearchResultView() {
		if (mAdapter != null)
			mAdapter = null;
		mAdapter = new SearchFriendsAdapter(this, resultList, this);
		searchListView.setAdapter(mAdapter);
	}

	/**
	 * 添加contact
	 * 
	 * @param view
	 */
	public void addContact(final String toAddUsername) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("token", mSpUtil.getToken());
			map.put("student_id", toAddUsername);
			String requestApi = ParamsUtils.buildParams(
					NetWorkApi.ADD_CHILD_API, map);
			MyAsyncHttp.get(this, requestApi, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						showToast("添加成功");
						sendBroadcast(new Intent("childChanged"));
						setResult(RESULT_OK);
						finish();
					} else {
						ShowToast.showShort(mContext, result);
					}

				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);
		}
	}

	public void onBack(View v) {
		finish();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAddThisFriend(int position) {
		addContact(resultList.get(position).id);
	}
}
